package com.itheima.reggie.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.domain.Category;
import com.itheima.reggie.domain.Dish;
import com.itheima.reggie.domain.Setmeal;
import com.itheima.reggie.domain.SetmealDish;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.mapper.SetmealDishMapper;
import com.itheima.reggie.mapper.SetmealMapper;
import com.itheima.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

//套餐
@Service
@Transactional
@Slf4j
public class SetmealServiceImpl implements SetmealService {

    @Autowired
    private SetmealMapper setmealMapper;

    @Autowired
    private SetmealDishMapper setmealDishMapper;

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private DishMapper dishMapper;



    //分页+模糊查询
    @Override
    public Page<Setmeal> findByPage(Integer pageNum, Integer pageSize, String name) {

        // 套餐条件分页查询
        // 构建条件
        LambdaQueryWrapper<Setmeal> qw = new LambdaQueryWrapper<>();
        qw.like(StrUtil.isNotBlank(name), Setmeal::getName, name);
        //  开启分页
        Page<Setmeal> page = new Page<>(pageNum, pageSize);
        // mapper查询
        page = setmealMapper.selectPage(page, qw);

        // 遍历套餐列表
        for (Setmeal setmeal : page.getRecords()) {
            // 根据category_id 查询并封装分类名称
            Category category = categoryMapper.selectById(setmeal.getCategoryId());
            setmeal.setCategoryName(category.getName());
            //  根据id查询并封装菜品列表
            LambdaQueryWrapper<SetmealDish> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(SetmealDish::getSetmealId, setmeal.getId());
            List<SetmealDish> setmealDishList = setmealDishMapper.selectList(wrapper);
            setmeal.setSetmealDishes(setmealDishList);
        }
        //返回组装后的数据
        return page;
    }


    //新增
    /*
        value=内存区域名称
        key=清理缓存的数据的key
        allEntries = true  清理区域下所有缓存数据
    */
    @Override
    @CacheEvict(value = "setmeal",allEntries = true)
    public void save(Setmeal setmeal) {
        // 1.新增套餐
        setmealMapper.insert(setmeal);
        log.info("套餐主键返回：" + setmeal.getImage());
        // 2.遍历前端提交套餐菜品列表
        List<SetmealDish> setmealDishList = setmeal.getSetmealDishes();
        for (SetmealDish setmealDish : setmealDishList) {
            // 关联套餐id
            setmealDish.setSetmealId(setmeal.getId());
            // 保存中间表
            setmealDishMapper.insert(setmealDish);
        }
    }

    // 删除套餐
    @Override
    @CacheEvict(value = "setmeal",allEntries = true)
    public void deleteBatch(List<Long> ids) {
        // 1.先查询套餐状态，是否有启售 select count(*) from setmeal where status=1 and id in(1,3,5);
        LambdaQueryWrapper<Setmeal> qw = new LambdaQueryWrapper<>();
        qw.in(Setmeal::getId,ids); // id in(1,3,5);
        qw.eq(Setmeal::getStatus,1); //   status=1
        Integer count = setmealMapper.selectCount(qw);
        if (count>0) {
            throw new CustomException("套餐中有启售状态，请先停售再删除~~~");
        }

        // 2.删套餐
        setmealMapper.deleteBatchIds(ids);

        // 3.删除套餐内菜品中间表
        LambdaQueryWrapper<SetmealDish> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(SetmealDish::getSetmealId,ids);
        setmealDishMapper.delete(wrapper);
    }

    //根据Id回显信息
    @Override
    public Setmeal findById(Long id) {
        Setmeal setmeal = setmealMapper.selectById(id);
        //根据setmeal的id从setmeal_dish表中查询列表
        LambdaQueryWrapper<SetmealDish> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(SetmealDish::getSetmealId, setmeal.getId());
        List<SetmealDish> setmealDisheList = setmealDishMapper.selectList(wrapper1);
        setmeal.setSetmealDishes(setmealDisheList);
        return setmeal;
    }

    //修改套餐
    @Override
    @CacheEvict(value = "setmeal",allEntries = true)
    public void update(Setmeal setmeal) {
        setmealMapper.updateById(setmeal);

        LambdaQueryWrapper<SetmealDish> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SetmealDish::getSetmealId, setmeal.getId());//WHERE dish_id = ?
        setmealDishMapper.delete(wrapper);

        List<SetmealDish> setmealDishList = setmeal.getSetmealDishes();
        if (CollectionUtil.isNotEmpty(setmealDishList)) {
            for (SetmealDish setmealDish : setmealDishList) {
                setmealDish.setSetmealId(setmeal.getId());//关联上套餐 主键返回id
                setmealDishMapper.insert(setmealDish);//执行保存
            }
        }
    }

    //启售/停售
    @Override
    public void status(Integer status, List<Long> ids) {
       /* for (Long id : ids) {
            //先用id查询查询到对象
            Setmeal setmeal = setmealMapper.selectById(id);
            //在给对象中的status赋值(把原来的值覆盖掉)
            setmeal.setStatus(status);
            //把对象写回修改表中的数据
            setmealMapper.updateById(setmeal);
        }*/

        // 条件对象
        LambdaQueryWrapper<Setmeal> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(Setmeal::getId, ids);
        // 修改实体
        Setmeal setmeal = new Setmeal();
        setmeal.setStatus(status);
        // 调用mapper
        setmealMapper.update(setmeal, wrapper);
    }

    //套餐展示
    //开启注解缓存
    /*
        value =  内存区域名称
        key =    方法的参数
           key（支持spel表达式）
     */
    @Cacheable( value = "setmeal" ,key = "#categoryId")
    @Override
    public List<Setmeal> findList(Long categoryId, Integer status) {
        log.info("查询MySQL");
        // 1.构建条件
        LambdaQueryWrapper<Setmeal> qw = new LambdaQueryWrapper<>();
        qw.eq(Setmeal::getCategoryId, categoryId);
        qw.eq(Setmeal::getStatus,status );
        // 2.执行查询并返回
        return setmealMapper.selectList(qw);
    }

    //查看套餐中的菜品
    @Override
    public List<SetmealDish> findDishById(Long id) {

       /* // 从中间表获取菜品信息
        LambdaQueryWrapper<SetmealDish> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SetmealDish::getSetmealId, id);
        List<SetmealDish> setmealDishList = setmealDishMapper.selectList(wrapper);

        // 创建一个集合封装返回菜品信息
        List<Dish> dishList = new ArrayList<>();

        //遍历
        for (SetmealDish setmealDish : setmealDishList) {
            //根据菜品id从菜品表查询菜品详情
            Dish dish = dishMapper.selectById(setmealDish.getDishId());
            dish.setCopies(setmealDish.getCopies());//设置份数
            dishList.add(dish);//添加到返回集合
        }

        //返回
        return dishList;*/

        //创建构造
        LambdaQueryWrapper<SetmealDish> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SetmealDish::getSetmealId,id);

        //查询套餐下菜品
        List<SetmealDish> setmealDishList = setmealDishMapper.selectList(wrapper);
        if (CollectionUtil.isNotEmpty(setmealDishList)) {
            //遍历
            for (SetmealDish setmealDish : setmealDishList) {
                //查询菜品
                Dish dish = dishMapper.selectById(setmealDish.getDishId());
                //将图片保存到中间表中
                setmealDish.setImage(dish.getImage());
            }
        }
        return setmealDishList;
    }
}
